#include "cityinfo.h"
#include <QFile>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>


cityInfo::cityInfo()
{

}

void cityInfo::putCityInfoToMap()
{
    QFile file(":/citycode.json");
    bool oFlag = file.open(QFile::ReadOnly);
    if(!oFlag)
    {
        //       qDebug() << "open citycode.json fault!";
        return;
    }
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull() && jsonDoc.isArray())
    {
        QJsonArray jsonArr = jsonDoc.array();
        for(QJsonValue val : jsonArr)
        {
            if(val.isObject())
            {
                QJsonObject jsonObj = val.toObject();
                QString cityCode = jsonObj["city_code"].toString();
                QString cityName = jsonObj["city_name"].toString();
                cityMap.insert(cityName, cityCode);
            }
        }
    }
}


QString cityInfo::getCityInfoFromMap(QString cityName)
{
    if(cityMap.isEmpty())
    {
        putCityInfoToMap();
    }
    // QMap<QString, QString>::const_iterator
    auto index = cityMap.find(cityName);
    if(index == cityMap.end())
    {
        index = cityMap.find(cityName + "市");
        if(index == cityMap.end())
        {
            index = cityMap.find(cityName + "县");
            if(index == cityMap.end())
            {
                index = cityMap.find(cityName + "区");
                if(index == cityMap.end())
                {
                    return NULL;
                }
            }
        }
    }
    return index.value();
}



